<template>
  <div class="template-detail">
    <van-nav-bar
      title="模板详情"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    >
      <template #right>
        <van-icon
          :name="template.isCollected ? 'star' : 'star-o'"
          :class="{ collected: template.isCollected }"
          @click="toggleCollect"
        />
      </template>
    </van-nav-bar>
    
    <div class="template-content">
      <!-- 模板头部信息 -->
      <div class="template-header">
        <div class="template-icon">
          <van-icon name="description" />
        </div>
        <div class="template-info">
          <h2 class="template-name">{{ template.name }}</h2>
          <div class="template-meta">
            <van-tag type="primary" size="small">{{ template.category }}</van-tag>
            <span class="meta-item">
              <van-icon name="eye-o" />
              {{ template.viewCount }}
            </span>
            <span class="meta-item">
              <van-icon name="star-o" />
              {{ template.collectCount }}
            </span>
          </div>
        </div>
      </div>
      
      <!-- 模板描述 -->
      <div class="template-description">
        <h3>模板说明</h3>
        <p>{{ template.description }}</p>
      </div>
      
      <!-- 适用场景 -->
      <div class="template-scenarios" v-if="template.scenarios && template.scenarios.length">
        <h3>适用场景</h3>
        <div class="scenario-list">
          <van-tag
            v-for="scenario in template.scenarios"
            :key="scenario"
            type="success"
            plain
            size="small"
          >
            {{ scenario }}
          </van-tag>
        </div>
      </div>
      
      <!-- 填写要点 -->
      <div class="template-tips" v-if="template.tips && template.tips.length">
        <h3>填写要点</h3>
        <div class="tips-list">
          <div
            v-for="(tip, index) in template.tips"
            :key="index"
            class="tip-item"
          >
            <van-icon name="info-o" />
            <span>{{ tip }}</span>
          </div>
        </div>
      </div>
      
      <!-- 模板预览 -->
      <div class="template-preview">
        <h3>模板预览</h3>
        <div class="preview-content">
          <div class="preview-text">{{ template.content }}</div>
        </div>
      </div>
      
      <!-- 相关法条 -->
      <div class="related-laws" v-if="template.relatedLaws && template.relatedLaws.length">
        <h3>相关法条</h3>
        <div class="law-list">
          <div
            v-for="law in template.relatedLaws"
            :key="law.id"
            class="law-item"
          >
            <div class="law-title">{{ law.title }}</div>
            <div class="law-content">{{ law.content }}</div>
          </div>
        </div>
      </div>
      
      <!-- 使用统计 -->
      <div class="template-stats">
        <h3>使用统计</h3>
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-number">{{ template.useCount }}</div>
            <div class="stat-label">使用次数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ template.successRate }}%</div>
            <div class="stat-label">成功率</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ template.rating }}</div>
            <div class="stat-label">评分</div>
          </div>
        </div>
      </div>
      
      <!-- 用户评价 -->
      <div class="template-reviews" v-if="reviews && reviews.length">
        <h3>用户评价</h3>
        <div class="review-list">
          <div
            v-for="review in reviews"
            :key="review.id"
            class="review-item"
          >
            <div class="review-header">
              <van-image
                class="avatar"
                :src="review.avatar || '/default-avatar.png'"
                round
                width="32"
                height="32"
              />
              <div class="review-info">
                <div class="username">{{ review.username }}</div>
                <van-rate
                  v-model="review.rating"
                  size="12"
                  readonly
                />
              </div>
              <div class="review-time">{{ formatTime(review.createTime) }}</div>
            </div>
            <div class="review-content">{{ review.content }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部操作栏 -->
    <div class="bottom-actions">
      <van-button
        type="primary"
        size="large"
        @click="useTemplate"
      >
        使用模板
      </van-button>
      <van-button
        size="large"
        plain
        @click="previewTemplate"
      >
        预览填写
      </van-button>
    </div>
  </div>
</template>

<script>
import { getTemplateDetail, collectTemplate } from '@/api/template'

export default {
  name: 'TemplateDetail',
  data() {
    return {
      template: {},
      reviews: [],
      loading: false
    }
  },
  created() {
    this.loadTemplateDetail()
  },
  methods: {
    async loadTemplateDetail() {
      try {
        this.loading = true
        const response = await getTemplateDetail(this.$route.params.id)
        this.template = response.data
        
        // 如果后端返回的数据结构不同，可能需要适配
        if (!this.template.scenarios) {
          this.template.scenarios = []
        }
        if (!this.template.tips) {
          this.template.tips = []
        }
        if (!this.template.relatedLaws) {
          this.template.relatedLaws = []
        }
        
        // 加载评价数据（如果有相关接口）
        this.loadReviews()
        
      } catch (error) {
        console.error('加载模板详情失败:', error)
        this.$toast.fail('加载失败')
        // 使用模拟数据作为后备
        this.loadMockData()
      } finally {
        this.loading = false
      }
    },
    loadReviews() {
      // 模拟用户评价数据（如果后端没有相关接口）
      this.reviews = [
        {
          id: 1,
          username: '维权成功者',
          avatar: '',
          rating: 5,
          content: '模板很实用，按照填写要点操作，成功拿到了经济补偿金。',
          createTime: new Date('2024-01-15')
        },
        {
          id: 2,
          username: '法律小白',
          avatar: '',
          rating: 4,
          content: '作为法律小白，这个模板帮了大忙，格式规范，要点清晰。',
          createTime: new Date('2024-01-10')
        }
      ]
    },
    loadMockData() {
      // 后备的模拟数据
      this.template = {
        id: this.$route.params.id,
        name: '劳动仲裁申请书',
        category: '劳动纠纷',
        description: '适用于劳动者与用人单位发生劳动争议时，向劳动仲裁委员会申请仲裁的标准格式文书。包含完整的申请要素和法律依据。',
        content: `劳动仲裁申请书

申请人：[姓名]，[性别]，[出生年月]，[民族]，[身份证号]，住址：[详细地址]，联系电话：[电话号码]

被申请人：[公司名称]
法定代表人：[姓名]
地址：[公司地址]
联系电话：[电话号码]

仲裁请求：
1. 请求确认申请人与被申请人之间存在劳动关系；
2. 请求被申请人支付申请人工资[具体金额]元；
3. 请求被申请人支付申请人经济补偿金[具体金额]元；
4. 请求被申请人承担本案仲裁费用。

事实与理由：
[详细描述劳动争议的事实经过、争议焦点和法律依据]

此致
[所在地]劳动人事争议仲裁委员会

申请人：[签名]
[申请日期]`,
        scenarios: ['工资拖欠', '违法解除', '经济补偿', '工伤赔偿'],
        tips: [
          '填写个人信息时务必准确无误，与身份证保持一致',
          '被申请人信息可通过企业信用信息公示系统查询',
          '仲裁请求要具体明确，金额要有依据',
          '事实与理由部分要条理清晰，有理有据',
          '准备好相关证据材料作为附件'
        ],
        relatedLaws: [
          {
            id: 1,
            title: '《劳动争议调解仲裁法》第二十八条',
            content: '申请人申请仲裁应当提交书面仲裁申请，并按照被申请人人数提交副本。'
          },
          {
            id: 2,
            title: '《劳动合同法》第四十七条',
            content: '经济补偿按劳动者在本单位工作的年限，每满一年支付一个月工资的标准向劳动者支付。'
          }
        ],
        viewCount: 1250,
        collectCount: 89,
        useCount: 456,
        successRate: 85,
        rating: 4.6,
        isCollected: false
      }
    },
    formatTime(time) {
      return new Date(time).toLocaleDateString()
    },
    async toggleCollect() {
      try {
        await collectTemplate(this.template.id)
        this.template.isCollected = !this.template.isCollected
        if (this.template.isCollected) {
          this.template.collectCount++
          this.$toast.success('收藏成功')
        } else {
          this.template.collectCount--
          this.$toast.success('取消收藏')
        }
      } catch (error) {
        console.error('收藏操作失败:', error)
        this.$toast.fail('操作失败')
      }
    },
    useTemplate() {
      this.$router.push(`/templates/fill/${this.template.id}`)
    },
    previewTemplate() {
      this.$dialog.alert({
        title: '模板预览',
        message: this.template.content,
        messageAlign: 'left'
      })
    }
  }
}
</script>

<style scoped>
.template-detail {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 80px;
}

.template-content {
  padding: 15px;
}

.template-header {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.template-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #1989fa, #1890ff);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  margin-right: 15px;
}

.template-info {
  flex: 1;
}

.template-name {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: bold;
}

.template-meta {
  display: flex;
  align-items: center;
  gap: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.template-description,
.template-scenarios,
.template-tips,
.template-preview,
.related-laws,
.template-stats,
.template-reviews {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 15px;
}

.template-description h3,
.template-scenarios h3,
.template-tips h3,
.template-preview h3,
.related-laws h3,
.template-stats h3,
.template-reviews h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: bold;
}

.template-description p {
  line-height: 1.6;
  color: #666;
  margin: 0;
}

.scenario-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tips-list {
  space-y: 10px;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 10px;
}

.tip-item .van-icon {
  color: #1989fa;
  margin-top: 2px;
}

.preview-content {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
}

.preview-text {
  font-family: monospace;
  line-height: 1.6;
  white-space: pre-line;
  color: #333;
}

.law-list {
  space-y: 15px;
}

.law-item {
  border-left: 3px solid #1989fa;
  padding-left: 15px;
  margin-bottom: 15px;
}

.law-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.law-content {
  color: #666;
  line-height: 1.5;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #1989fa;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.review-list {
  space-y: 15px;
}

.review-item {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
  margin-bottom: 15px;
}

.review-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  margin-right: 10px;
}

.review-info {
  flex: 1;
}

.username {
  font-weight: bold;
  margin-bottom: 5px;
}

.review-time {
  font-size: 12px;
  color: #999;
}

.review-content {
  color: #666;
  line-height: 1.5;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 15px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
}

.bottom-actions .van-button {
  flex: 1;
}

.collected {
  color: #ffa502;
}
</style>